package cn.itsource.config;



import cn.itsource.Utils.JSONResult;
import cn.itsource.Utils.UseTools;
import cn.itsource.domain.sys_user;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

// Description:   自定义的登录拦截器
@Configuration// 将三层之外的类交给Spring管理
public class LoginInterceptor implements HandlerInterceptor {


   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       // 1. 拿到session中存储的用户信息
       sys_user userInfo = UseTools.getUserInfo(request);
      // 2. 判断用户信息是否存在
      if(userInfo==null){
           // 当前用户没有登录
           // 1. 设置返回值的数据类型
           response.setContentType("application/json;charset=utf-8");
            // 2. 自定义返回的对象
           JSONResult jsonResult = new JSONResult(false, "当前未登录,请重新登陆!!!", "666", null);

          // 3. 拿到响应对象
           PrintWriter writer = response.getWriter();
           // 4. 将对象转换成json字符串
           String sjson = JSONObject.toJSONString(jsonResult);
           // 4. 返回响应数据
          writer.write(sjson);
           return false;
        }

        return true;


   }
}
